<?php

/**
 * 客户资料模型
 */
class Client_model extends CI_Model {
    
    const TN = "clients";

    /**
     * 
     * @param type $id
     * @return array
     */
    public function get($id) {
        $query = $this->db->get_where(self::TN, array('c_id' => $id));
        
        return $query->first_row("array");
    }

    /**
     * 新client数组
     * @return type
     */
    public function new_client() {
        return array(
            'c_id' => 0,
            'c_name'=> '',
            'c_name_en'=> '',
            'c_addr'=> '',
            'c_addr_en'=> '',
            'c_mailing_addr'=> '',
            'c_mailing_addr_en'=> '',
            'c_licence_type'=> '',
            'c_licence_number'=> '',
            'c_country'=> '',
            'contact_ids' => ''
        );
    }
    
    public function licence_types() {
        return array('企业注册号', '身份证', '护照');
    }
    
    public function insert($client) {
        $this->db->insert(self::TN, $client);
    }
    
    public function update($id, $client) {
        $this->db->where('c_id', $id);
        $this->db->update(self::TN, $client);
    }
    
    public function delete($id) {
        $this->db->delete(self::TN, array('c_id' => $id));
    }
    
    public function insert_id() {
        return $this->db->insert_id();
    }
    
    /**
     * 
     * @return array(array('id' => '', 'name' => ''), ...)
     */
    public function fetch_names() {
        $this->db->select('c_id as id, c_name as name');
        $query = $this->db->get(self::TN);
        
        return $query->result_array();
    }

    /**
     * 
     * @param type $conditions
     * @param type $per_page 默认0表示取所有记录
     * @param type $page
     * @return array
     */
    public function fetch_array($conditions, $per_page = 0, $page = 0) {
        $this->_set_where($conditions);
        if ($per_page > 0) {
            $offset = ($page - 1) * $per_page;
            $this->db->limit($per_page, $offset);
        }
        $this->db->order_by('c_id', 'desc');

        return $this->db->get(self::TN)->result_array();
    }
    
    /**
     * 返回记录总数
     * param $conditions
     */
    public function fetch_count($conditions) {
        $this->_set_where($conditions);
        $this->db->from(self::TN);
        
        return $this->db->count_all_results();
    }
    
    /**
     * 设置where
     * @param type $conditions
     */
    private function _set_where($conditions) {
        if (isset($conditions['keyword']) && $conditions['keyword'] != '') {
            $this->db->like('c_name', $conditions['keyword']);
            $this->db->or_like('c_name_en', $conditions['keyword']);
        }
    }
}
